<template>
  <div class="training-page">
    <!-- Header -->
    <van-nav-bar title="Training" fixed placeholder>
      <template #right>
        <van-icon name="search" size="18" @click="showSearch" />
      </template>
    </van-nav-bar>

    <!-- Filter Tabs -->
    <van-tabs v-model:active="activeTab" @change="onTabChange" sticky>
      <van-tab title="Characters" name="characters">
        <!-- Character Filters -->
        <div class="filters">
          <van-dropdown-menu>
            <van-dropdown-item v-model="filters.difficulty" :options="difficultyOptions" />
            <van-dropdown-item v-model="filters.category" :options="categoryOptions" />
            <van-dropdown-item v-model="filters.sortBy" :options="sortOptions" />
          </van-dropdown-menu>
        </div>

        <!-- Characters List -->
        <div class="characters-list">
          <div class="character-card" v-for="character in characters" :key="character.id"
            @click="selectCharacter(character)">
            <div class="character-avatar">
              <van-image :src="character.avatar_url" width="60" height="60" round fit="cover" />
              <van-icon name="star" class="favorite-icon" :class="{ active: character.is_favorited }"
                @click.stop="toggleFavorite(character)" />
            </div>
            <div class="character-info">
              <div class="character-name">{{ character.name }}</div>
              <div class="character-description">{{ character.description }}</div>
              <div class="character-tags">
                <van-tag v-for="tag in character.tags.slice(0, 2)" :key="tag" type="primary">
                  {{ tag }}
                </van-tag>
              </div>
              <div class="character-stats">
                <div class="stat">
                  <van-icon name="star-o" size="12" />
                  <span>{{ character.rating?.toFixed?.(1) || 'N/A' }}</span>
                </div>
                <div class="stat">
                  <van-icon name="user-o" size="12" />
                  <span>{{ character.total_sessions || 0 }}</span>
                </div>
                <div class="difficulty-badge" :class="character.difficulty_text?.toLowerCase()">
                  {{ character.difficulty_text }}
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- Load More -->
        <div class="load-more" v-if="hasMoreCharacters">
          <van-button :loading="loading" @click="loadMoreCharacters" block type="primary" plain>
            Load More
          </van-button>
        </div>
      </van-tab>

      <van-tab title="Scenarios" name="scenarios">
        <!-- Scenarios List -->
        <div class="scenarios-list">
          <div class="scenario-card" v-for="scenario in scenarios" :key="scenario.id" @click="selectScenario(scenario)">
            <div class="scenario-thumbnail">
              <van-image :src="scenario.thumbnail" width="80" height="60" fit="cover" radius="8" />
            </div>
            <div class="scenario-info">
              <div class="scenario-title">{{ scenario.title }}</div>
              <div class="scenario-description">{{ scenario.description }}</div>
              <div class="scenario-meta">
                <div class="meta-item">
                  <van-icon name="clock-o" size="12" />
                  <span>{{ scenario.estimated_duration || 15 }}min</span>
                </div>
                <div class="meta-item">
                  <van-icon name="star-o" size="12" />
                  <span>{{ scenario.rating?.toFixed?.(1) }}</span>
                </div>
                <div class="difficulty-badge" :class="scenario.difficulty">
                  {{ scenario.difficulty }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </van-tab>

      <van-tab title="My Training" name="history">
        <!-- Training History -->
        <div class="training-history">
          <div class="history-stats">
            <div class="stat-card">
              <div class="stat-value">{{ userStats.totalSessions }}</div>
              <div class="stat-label">Total Sessions</div>
            </div>
            <div class="stat-card">
              <div class="stat-value">{{ userStats.successRate }}%</div>
              <div class="stat-label">Success Rate</div>
            </div>
            <div class="stat-card">
              <div class="stat-value">{{ userStats.currentStreak }}</div>
              <div class="stat-label">Current Streak</div>
            </div>
          </div>

          <div class="recent-sessions">
            <h3>Recent Sessions</h3>
            <div class="session-list">
              <div class="session-item" v-for="session in recentSessions" :key="session.id"
                @click="viewSessionDetail(session)">
                <div class="session-info">
                  <div class="session-title">{{ session.characterName }} - {{ session.scenarioTitle }}</div>
                  <div class="session-meta">
                    <span class="session-date">{{ formatTime(session.completedAt) }}</span>
                    <span class="session-duration">{{ Math.floor(session.duration / 60) }}min</span>
                  </div>
                </div>
                <div class="session-result">
                  <van-icon :name="session.successAchieved ? 'success' : 'cross'"
                    :color="session.successAchieved ? '#07c160' : '#ee0a24'" />
                </div>
              </div>
            </div>
          </div>
        </div>
      </van-tab>
    </van-tabs>

    <!-- Character Selection Modal -->
    <van-popup v-model:show="showCharacterModal" position="bottom" :style="{ height: '70%' }">
      <div class="character-modal" v-if="selectedCharacter">
        <div class="modal-header">
          <h3>{{ selectedCharacter.name }}</h3>
          <van-button type="primary" size="small" @click="startTrainingWithCharacter">
            Start Training
          </van-button>
        </div>
        <div class="modal-content">
          <div class="character-detail">
            <van-image :src="selectedCharacter.avatar_url" width="80" height="80" round fit="cover" />
            <div class="character-personality">
              <h4>Personality</h4>
              <div class="personality-tags">
                <van-tag :type="'success'">
                  {{ selectedCharacter.personality_type }}
                </van-tag>
              </div>
            </div>
            <div class="character-specialties">
              <h4>Specialties</h4>
              <div class="specialty-tags">
                <van-tag v-for="tag in selectedCharacter.tags" :key="tag" type="primary">
                  {{ tag }}
                </van-tag>
              </div>
            </div>
          </div>
        </div>
      </div>
    </van-popup>

    <!-- Search Dialog -->
    <van-dialog v-model:show="showSearchDialog" title="Search Training Content" show-cancel-button
      @confirm="performSearch">
      <van-field v-model="searchQuery" placeholder="Search characters, scenarios, or skills..." clearable
        @keyup.enter="performSearch" />
    </van-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import { trainingApi, type AiCharacter, type TrainingScenario } from '@/api/training'

const router = useRouter()

const activeTab = ref('characters')
const loading = ref(false)
const showCharacterModal = ref(false)
const selectedCharacter = ref<AiCharacter | null>(null)

const filters = reactive({
  difficulty: '',
  category: '',
  sortBy: 'popularity' as 'rating' | 'popularity' | 'newest'
})

// Data from API
const characters = ref<AiCharacter[]>([])
const scenarios = ref<TrainingScenario[]>([])
const hasMoreCharacters = ref(true)

// Utility function
const formatTime = (timestamp: string) => {
  const now = Date.now()
  const time = new Date(timestamp).getTime()
  const diff = now - time
  const hours = Math.floor(diff / (1000 * 60 * 60))

  if (hours < 1) {
    return 'Just now'
  } else if (hours < 24) {
    return `${hours}h ago`
  } else {
    const days = Math.floor(hours / 24)
    return `${days}d ago`
  }
}

// Load characters from API
const loadCharacters = async () => {
  try {
    loading.value = true
    const response = await trainingApi.getCharacters({
      difficulty_level: filters.difficulty ? parseInt(filters.difficulty) : undefined
    })

    if (response.success && response.data) {
      characters.value = response.data
    }
  } catch (error) {
    console.error('Failed to load characters:', error)
    showToast('Failed to load characters')
  } finally {
    loading.value = false
  }
}

// Load scenarios from API
const loadScenarios = async () => {
  try {
    loading.value = true
    const response = await trainingApi.getScenarios({
      difficulty_level: filters.difficulty ? parseInt(filters.difficulty) : undefined
    })

    if (response.success && response.data) {
      scenarios.value = response.data
    }
  } catch (error) {
    console.error('Failed to load scenarios:', error)
    showToast('Failed to load scenarios')
  } finally {
    loading.value = false
  }
}

// Mock user stats
const userStats = reactive({
  totalSessions: 24,
  successRate: 78,
  currentStreak: 5
})

// Mock recent sessions
const recentSessions = ref([
  {
    id: 1,
    characterName: 'Emma',
    scenarioTitle: 'Coffee Shop Conversation',
    completedAt: new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString(),
    duration: 480,
    successAchieved: true
  },
  {
    id: 2,
    characterName: 'Alex',
    scenarioTitle: 'Job Interview',
    completedAt: new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString(),
    duration: 720,
    successAchieved: false
  }
])

// Filter options
const difficultyOptions = [
  { text: 'All Levels', value: '' },
  { text: 'Beginner', value: 'beginner' },
  { text: 'Intermediate', value: 'intermediate' },
  { text: 'Advanced', value: 'advanced' }
]

const categoryOptions = [
  { text: 'All Categories', value: '' },
  { text: 'Social', value: 'social' },
  { text: 'Professional', value: 'professional' },
  { text: 'Casual', value: 'casual' }
]

const sortOptions = [
  { text: 'Most Popular', value: 'popularity' },
  { text: 'Highest Rated', value: 'rating' },
  { text: 'Newest', value: 'newest' }
]

const onTabChange = (name: string) => {
  if (name === 'scenarios' && scenarios.value.length === 0) {
    loadScenarios()
  }
}

const loadMoreCharacters = async () => {
  try {
    loading.value = true
    // In a real implementation, this would handle pagination
    showToast('No more characters to load')
    hasMoreCharacters.value = false
  } catch (error) {
    showToast('Failed to load more characters')
  } finally {
    loading.value = false
  }
}

// loadScenarios function already defined above

const selectCharacter = (character: AiCharacter) => {
  selectedCharacter.value = character
  showCharacterModal.value = true
}

const selectScenario = (scenario: TrainingScenario) => {
  router.push(`/training/scenario/${scenario.id}`)
}

const toggleFavorite = async (character: AiCharacter) => {
  try {
    if (character.is_favorited) {
      await trainingApi.unfavoriteCharacter(character.id)
      character.is_favorited = false
      showToast('Removed from favorites')
    } else {
      await trainingApi.favoriteCharacter(character.id)
      character.is_favorited = true
      showToast('Added to favorites')
    }
  } catch (error) {
    console.error('Failed to update favorite:', error)
    showToast('Failed to update favorite')
  }
}

const startTrainingWithCharacter = () => {
  if (selectedCharacter.value) {
    router.push(`/training/character/${selectedCharacter.value.id}`)
  }
  showCharacterModal.value = false
}

const viewSessionDetail = (session: any) => {
  router.push(`/training/session/${session.id}`)
}

const showSearchDialog = ref(false)
const searchQuery = ref('')

const showSearch = () => {
  showSearchDialog.value = true
}

const performSearch = () => {
  if (!searchQuery.value.trim()) {
    showToast('Please enter a search term')
    return
  }

  // Filter characters and scenarios based on search query
  const query = searchQuery.value.toLowerCase()
  const filteredCharacters = characters.value.filter(character =>
    character.name.toLowerCase().includes(query) ||
    character.description.toLowerCase().includes(query) ||
    character.tags.some(tag => tag.toLowerCase().includes(query))
  )

  const filteredScenarios = scenarios.value.filter(scenario =>
    (scenario.title || scenario.name || '').toLowerCase().includes(query) ||
    scenario.description.toLowerCase().includes(query) ||
    (scenario.category || '').toLowerCase().includes(query)
  )

  if (filteredCharacters.length === 0 && filteredScenarios.length === 0) {
    showToast('No results found')
  } else {
    showToast(`Found ${filteredCharacters.length} characters and ${filteredScenarios.length} scenarios`)
    // In a real app, you would update the displayed results
  }

  showSearchDialog.value = false
  searchQuery.value = ''
}

// Load initial data
onMounted(() => {
  loadCharacters()
})
</script>

<style lang="scss" scoped>
.training-page {
  min-height: 100vh;
  background: $background-color;
  padding-bottom: $tabbar-height;
}

.filters {
  background: $white;
  border-bottom: 1px solid $border-color-light;
}

.characters-list {
  padding: $spacing-md;

  .character-card {
    background: $white;
    border-radius: $border-radius-lg;
    padding: $spacing-md;
    margin-bottom: $spacing-md;
    display: flex;
    gap: $spacing-md;
    box-shadow: $box-shadow-light;
    cursor: pointer;
    transition: transform 0.2s ease;

    &:active {
      transform: scale(0.98);
    }

    .character-avatar {
      position: relative;

      .favorite-icon {
        position: absolute;
        top: -4px;
        right: -4px;
        background: $white;
        border-radius: 50%;
        padding: 4px;
        color: $gray-5;
        box-shadow: $box-shadow-light;

        &.active {
          color: $warning-color;
        }
      }
    }

    .character-info {
      flex: 1;

      .character-name {
        font-size: $font-size-md;
        font-weight: $font-weight-medium;
        color: $text-color;
        margin-bottom: $spacing-xs;
      }

      .character-description {
        font-size: $font-size-sm;
        color: $text-color-3;
        margin-bottom: $spacing-sm;
        line-height: 1.4;
      }

      .character-tags {
        margin-bottom: $spacing-sm;
        display: flex;
        gap: $spacing-xs;
      }

      .character-stats {
        display: flex;
        align-items: center;
        gap: $spacing-md;

        .stat {
          display: flex;
          align-items: center;
          gap: 4px;
          font-size: $font-size-xs;
          color: $text-color-3;
        }

        .difficulty-badge {
          font-size: $font-size-xs;
          padding: 2px 6px;
          border-radius: 4px;
          font-weight: $font-weight-medium;

          &.beginner {
            background: #e8f5e8;
            color: #52c41a;
          }

          &.intermediate {
            background: #fff7e6;
            color: #fa8c16;
          }

          &.advanced {
            background: #fff2f0;
            color: #f5222d;
          }
        }
      }
    }
  }
}

.scenarios-list {
  padding: $spacing-md;

  .scenario-card {
    background: $white;
    border-radius: $border-radius-lg;
    padding: $spacing-md;
    margin-bottom: $spacing-md;
    display: flex;
    gap: $spacing-md;
    box-shadow: $box-shadow-light;
    cursor: pointer;
    transition: transform 0.2s ease;

    &:active {
      transform: scale(0.98);
    }

    .scenario-info {
      flex: 1;

      .scenario-title {
        font-size: $font-size-md;
        font-weight: $font-weight-medium;
        color: $text-color;
        margin-bottom: $spacing-xs;
      }

      .scenario-description {
        font-size: $font-size-sm;
        color: $text-color-3;
        margin-bottom: $spacing-sm;
        line-height: 1.4;
      }

      .scenario-meta {
        display: flex;
        align-items: center;
        gap: $spacing-md;

        .meta-item {
          display: flex;
          align-items: center;
          gap: 4px;
          font-size: $font-size-xs;
          color: $text-color-3;
        }
      }
    }
  }
}

.training-history {
  padding: $spacing-md;

  .history-stats {
    display: flex;
    gap: $spacing-md;
    margin-bottom: $spacing-lg;

    .stat-card {
      flex: 1;
      background: $white;
      border-radius: $border-radius-lg;
      padding: $spacing-md;
      text-align: center;
      box-shadow: $box-shadow-light;

      .stat-value {
        font-size: $font-size-xl;
        font-weight: $font-weight-bold;
        color: $primary-color;
        margin-bottom: $spacing-xs;
      }

      .stat-label {
        font-size: $font-size-xs;
        color: $text-color-3;
      }
    }
  }

  .recent-sessions {
    h3 {
      font-size: $font-size-lg;
      color: $text-color;
      margin-bottom: $spacing-md;
    }

    .session-list {
      background: $white;
      border-radius: $border-radius-lg;
      overflow: hidden;

      .session-item {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: $spacing-md;
        border-bottom: 1px solid $border-color-light;
        cursor: pointer;

        &:last-child {
          border-bottom: none;
        }

        &:active {
          background: $gray-1;
        }

        .session-info {
          .session-title {
            font-size: $font-size-sm;
            color: $text-color;
            margin-bottom: 4px;
          }

          .session-meta {
            display: flex;
            gap: $spacing-md;
            font-size: $font-size-xs;
            color: $text-color-3;
          }
        }
      }
    }
  }
}

.load-more {
  padding: $spacing-md;
}

.character-modal {
  padding: $spacing-lg;

  .modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: $spacing-lg;
    padding-bottom: $spacing-md;
    border-bottom: 1px solid $border-color-light;

    h3 {
      font-size: $font-size-lg;
      color: $text-color;
    }
  }

  .character-detail {
    text-align: center;

    .character-personality,
    .character-specialties {
      margin-top: $spacing-lg;

      h4 {
        font-size: $font-size-md;
        color: $text-color;
        margin-bottom: $spacing-sm;
      }

      .personality-tags,
      .specialty-tags {
        display: flex;
        flex-wrap: wrap;
        gap: $spacing-xs;
        justify-content: center;
      }
    }
  }
}
</style>